package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2025-07-30 11:29
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void read(Long id) {
        //1.创建读写锁对象
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("lock:" + id);
        //2.获取读锁对象
        RLock lock = readWriteLock.readLock();
        //3.获取读锁
        lock.lock(5, TimeUnit.SECONDS);
        try {
            log.info("获取读锁成功，正在执行读取：{}的记录", id);
        } finally {
            //故意不释放读锁，让其5s后自动失效
            //lock.unlock();
        }
    }

    @Override
    public void write(Long id) {
        //1.创建读写锁对象
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("lock:" + id);
        //2.获取写锁对象
        RLock lock = readWriteLock.writeLock();
        //3.获取写锁
        lock.lock(5, TimeUnit.SECONDS);
        try {
            log.info("获取写锁成功，正在执行写：{}的记录", id);
        } finally {
            //故意不释放写锁，让其5s后自动失效
            //lock.unlock();
        }
    }
}
